import { IJson } from "../../interface/type"
import utilTool from "../../util/tool"
import { vbenConfig } from '../../vbenConfig'

export function editTemp(pageConfig: IJson): string {
  const editFileName = pageConfig.list.name.replace('列表', '')
  const modifyName = pageConfig.modify?.fileName ? utilTool.firstUp(pageConfig.modify.fileName) : 'Modify'
  const apiFileName = pageConfig.filePath ? pageConfig.filePath : vbenConfig.baseUrl.replace(/\//g, '')

  return `<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
    >
  <BasicForm @register="registerForm" /></BasicDrawer>
</template>
<script lang = "ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchemas } from './${pageConfig.modify.fileName}.data';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { ${ pageConfig.modify.apiName} } from '/@/api/${vbenConfig.modelName}/${apiFileName}';
import { useMessage } from '/@/hooks/web/useMessage';
export default defineComponent({
  name: '${modifyName}Drawer',
  components: { BasicDrawer, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);
    const id = ref(null);
    const { createMessage } = useMessage();
    // const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
      labelWidth: 90,
      schemas: formSchemas,
      showActionButtonGroup: false,
      baseColProps: { lg: 12, md: 24 },
    });

    const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      resetFields();
      setDrawerProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      id.value = !!data?.record?.id ? data.record.id : null

      if (unref(isUpdate)) {
        setFieldsValue({
          ...data.record,
        });
      }
      // const treeData = await getMenuList();
      // updateSchema({
      //   field: 'parentMenu',
      //   componentProps: { treeData },
      // });
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增${editFileName}' : '编辑${editFileName}'));

    async function handleSubmit() {
      try {
        await validate();
        const values = getFieldsValue()
        if (isUpdate.value) {
          values.id = id.value;
        }
        setDrawerProps({ confirmLoading: true });
        await ${ pageConfig.modify.apiName } (values);
        createMessage.success(getTitle.value + '成功！');
        closeDrawer();
        emit('success');
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }

    return { registerDrawer, registerForm, getTitle, handleSubmit };
  },
});
</script>
`
}
